<template>
  <div class="medicine-receive-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">💊 药品领用管理</h1>
          <p class="page-subtitle">为老人提供及时、准确的药品服务，守护健康每一天</p>
        </div>
        <div class="stats-card">
          <div class="stat-item">
            <div class="stat-value">{{ medicines.length }}</div>
            <div class="stat-label">可用药品</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ elders.length }}</div>
            <div class="stat-label">负责老人</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ lowStockMedicines.length }}</div>
            <div class="stat-label">库存预警</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ todayRecords.length }}</div>
            <div class="stat-label">今日领用</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="form-container">
        <el-card class="form-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">📝 药品领用申请</span>
              <el-tag type="success" effect="dark">关爱服务</el-tag>
            </div>
          </template>

          <el-form :model="form" label-width="140px" @submit.prevent="submit">
            <el-form-item label="👵 选择老人">
              <el-select 
                v-model="form.elderId" 
                filterable 
                placeholder="请选择需要用药的老人"
                style="width: 100%"
              >
                <el-option 
                  v-for="e in elders" 
                  :key="e.elderId" 
                  :label="`${e.name}（${e.roomNumber || '未分配'}）`" 
                  :value="e.elderId" 
                />
              </el-select>
            </el-form-item>

            <el-form-item label="💊 选择药品">
              <el-select 
                v-model="form.medicineId" 
                filterable 
                placeholder="请选择需要领用的药品"
                style="width: 100%"
              >
                <el-option 
                  v-for="m in medicines" 
                  :key="m.medicineId" 
                  :label="`${m.medicineName}（库存：${m.quantity} ${m.unit || '盒'}）`" 
                  :value="m.medicineId" 
                />
              </el-select>
            </el-form-item>

            <el-form-item label="📦 领用数量">
              <el-input-number 
                v-model="form.quantity" 
                :min="1" 
                :max="getMaxQuantity()"
                controls-position="right"
                placeholder="请输入领用数量"
              />
              <div class="quantity-tip" v-if="form.medicineId">
                最多可领用 {{ getMaxQuantity() }} {{ getCurrentMedicineUnit() }}
              </div>
            </el-form-item>

            <el-form-item label="📋 用法说明">
              <el-input 
                type="textarea" 
                v-model="form.usageDesc" 
                :rows="3"
                placeholder="请详细说明药品使用方法，例如：每日2次，每次1片，饭后服用"
                maxlength="200"
                show-word-limit
              />
              <div class="quick-usage-buttons">
                <el-button size="small" @click="fillCommonUsage('daily')">每日用药</el-button>
                <el-button size="small" @click="fillCommonUsage('weekly')">每周用药</el-button>
                <el-button size="small" @click="fillCommonUsage('emergency')">紧急用药</el-button>
                <el-button size="small" @click="fillCommonUsage('external')">外用药品</el-button>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button 
                type="primary" 
                native-type="submit" 
                :loading="loading"
                size="large"
                class="submit-btn"
              >
                <el-icon><Check /></el-icon>
                提交领用申请
              </el-button>
              <el-button 
                @click="reset" 
                size="large"
                class="reset-btn"
              >
                <el-icon><Refresh /></el-icon>
                重新填写
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 侧边信息栏 -->
      <div class="sidebar">
        <el-card class="info-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">💡 温馨提示</span>
            </div>
          </template>
          <div class="tips-content">
            <div class="tip-item">
              <el-icon><InfoFilled /></el-icon>
              <span>请仔细核对老人信息和药品名称</span>
            </div>
            <div class="tip-item">
              <el-icon><WarningFilled /></el-icon>
              <span>注意药品库存数量，避免领用过多</span>
            </div>
            <div class="tip-item">
              <el-icon><SuccessFilled /></el-icon>
              <span>详细填写用法说明，确保用药安全</span>
            </div>
          </div>
        </el-card>

        <el-card class="recent-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">📋 最近领用记录</span>
            </div>
          </template>
          <div class="recent-list" v-if="recentRecords.length > 0">
            <div 
              v-for="record in recentRecords" 
              :key="record.id"
              class="recent-item"
            >
              <div class="record-info">
                <div class="elder-name">{{ getElderName(record.elderId) }}</div>
                <div class="medicine-info">{{ getMedicineName(record.medicineId) }} × {{ record.quantity }}</div>
              </div>
              <div class="record-time">{{ formatTime(record.createdTime) }}</div>
            </div>
          </div>
          <div class="empty-state" v-else>
            <el-icon><Document /></el-icon>
            <p>暂无领用记录</p>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getMedicineList, addMedicineReceiveRecord } from '@/api/medicine'
import { elderApi } from '@/api/elder'
import { ElMessage } from 'element-plus'
import { Check, Refresh, InfoFilled, WarningFilled, SuccessFilled, Document, Bell } from '@element-plus/icons-vue'

const form = ref({
  elderId: null,
  medicineId: null,
  quantity: 1,
  usageDesc: ''
})

const elders = ref([])
const medicines = ref([])
const loading = ref(false)
const recentRecords = ref([])
const allRecords = ref([])

// 计算属性
const lowStockMedicines = computed(() => {
  return medicines.value.filter(medicine => medicine.quantity <= 10)
})

const todayRecords = computed(() => {
  const today = new Date().toDateString()
  return allRecords.value.filter(record => 
    new Date(record.createdTime).toDateString() === today
  )
})

const selectedElder = computed(() => {
  return elders.value.find(e => e.elderId === form.value.elderId)
})

const selectedMedicine = computed(() => {
  return medicines.value.find(m => m.medicineId === form.value.medicineId)
})

onMounted(async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const [eRes, mRes] = await Promise.all([
      elderApi.getElders({ caregiverId: userInfo.caregiverId }),
      getMedicineList()
    ])
    elders.value = eRes.data || []
    medicines.value = mRes.data || []
    // 加载领用记录
    loadRecords()
  } catch (error) {
    console.error('加载数据失败:', error)
  }
})

// 获取当前选中药品的最大可领用数量
const getMaxQuantity = () => {
  if (!form.value.medicineId) return 100
  const medicine = medicines.value.find(m => m.medicineId === form.value.medicineId)
  return medicine ? medicine.quantity : 100
}

// 获取当前选中药品的单位
const getCurrentMedicineUnit = () => {
  if (!form.value.medicineId) return '盒'
  const medicine = medicines.value.find(m => m.medicineId === form.value.medicineId)
  return medicine?.unit || '盒'
}

// 获取老人姓名
const getElderName = (elderId) => {
  const elder = elders.value.find(e => e.elderId === elderId)
  return elder?.name || '未知老人'
}

// 获取药品名称
const getMedicineName = (medicineId) => {
  const medicine = medicines.value.find(m => m.medicineId === medicineId)
  return medicine?.medicineName || '未知药品'
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 加载领用记录
const loadRecords = () => {
  // 模拟数据
  allRecords.value = [
    {
      id: 1,
      elderId: elders.value[0]?.elderId,
      medicineId: medicines.value[0]?.medicineId,
      quantity: 2,
      createdTime: new Date(Date.now() - 2 * 60 * 60 * 1000),
      status: 'approved'
    },
    {
      id: 2,
      elderId: elders.value[1]?.elderId,
      medicineId: medicines.value[1]?.medicineId,
      quantity: 1,
      createdTime: new Date(Date.now() - 5 * 60 * 60 * 1000),
      status: 'approved'
    },
    {
      id: 3,
      elderId: elders.value[0]?.elderId,
      medicineId: medicines.value[2]?.medicineId,
      quantity: 3,
      createdTime: new Date(Date.now() - 24 * 60 * 60 * 1000),
      status: 'approved'
    }
  ].filter(record => record.elderId && record.medicineId)
  
  // 最近记录显示最新的5条
  recentRecords.value = allRecords.value
    .sort((a, b) => new Date(b.createdTime) - new Date(a.createdTime))
    .slice(0, 5)
}

// 检查库存预警
const checkStockWarning = () => {
  if (lowStockMedicines.value.length > 0) {
    ElMessage.warning({
      message: `有 ${lowStockMedicines.value.length} 种药品库存不足，请及时补充`,
      duration: 5000
    })
  }
}

const submit = async () => {
  if (!form.value.elderId || !form.value.medicineId) {
    ElMessage.warning('请选择老人和药品')
    return
  }
  
  if (form.value.quantity > getMaxQuantity()) {
    ElMessage.warning(`领用数量不能超过库存数量 ${getMaxQuantity()} ${getCurrentMedicineUnit()}`)
    return
  }
  
  if (!form.value.usageDesc.trim()) {
    ElMessage.warning('请填写药品用法说明，确保用药安全')
    return
  }
  
  loading.value = true
  try {
    await addMedicineReceiveRecord({
      ...form.value,
      caregiverId: JSON.parse(localStorage.getItem('userInfo')).caregiverId || 1
    })
    ElMessage.success('领用申请提交成功！我们将尽快为您处理')
    reset()
    loadRecords() // 刷新记录
    checkStockWarning() // 检查库存预警
  } catch {
    ElMessage.error('申请失败，库存可能不足或系统繁忙，请稍后重试')
  } finally {
    loading.value = false
  }
}

const reset = () => {
  form.value = {
    elderId: null,
    medicineId: null,
    quantity: 1,
    usageDesc: ''
  }
}

// 自动填充常用用法说明
const fillCommonUsage = (type) => {
  const commonUsages = {
    'daily': '每日2次，每次1片，饭后服用',
    'weekly': '每周1次，每次2片，早餐后服用',
    'emergency': '必要时服用，每次1片，症状缓解后停止',
    'external': '外用，每日2-3次，涂抹于患处'
  }
  form.value.usageDesc = commonUsages[type] || ''
}
</script>

<style scoped>
.medicine-receive-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 30px;
  margin-bottom: 30px;
  color: white;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.title-section .page-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin: 0 0 10px 0;
  background: linear-gradient(45deg, #fff, #e3f2fd);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.title-section .page-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.stats-card {
  display: flex;
  gap: 30px;
  background: rgba(255, 255, 255, 0.2);
  padding: 20px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 2rem;
  font-weight: 700;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.8;
}

.main-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
  max-width: 1400px;
  margin: 0 auto;
}

.form-card, .info-card, .recent-card {
  border-radius: 16px;
  border: none;
  transition: all 0.3s ease;
}

.form-card:hover, .info-card:hover, .recent-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 1.3rem;
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #34495e;
}

.quantity-tip {
  font-size: 0.85rem;
  color: #7f8c8d;
  margin-top: 8px;
}

.submit-btn, .reset-btn {
  border-radius: 10px;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.reset-btn {
  border-color: #dcdfe6;
}

.reset-btn:hover {
  border-color: #667eea;
  color: #667eea;
}

.tips-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 10px;
  transition: all 0.3s ease;
}

.tip-item:hover {
  background: #e3f2fd;
  transform: translateX(5px);
}

.tip-item .el-icon {
  font-size: 1.2rem;
  color: #667eea;
}

.recent-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.recent-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 10px;
  transition: all 0.3s ease;
}

.recent-item:hover {
  background: #e3f2fd;
  transform: translateX(5px);
}

.record-info .elder-name {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
}

.record-info .medicine-info {
  font-size: 0.9rem;
  color: #7f8c8d;
}

.record-time {
  font-size: 0.8rem;
  color: #95a5a6;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #bdc3c7;
}

.empty-state .el-icon {
  font-size: 3rem;
  margin-bottom: 15px;
}

.empty-state p {
  margin: 0;
  font-size: 0.9rem;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    grid-template-columns: 1fr;
  }
  
  .header-content {
    flex-direction: column;
    text-align: center;
  }
  
  .stats-card {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .page-header {
    padding: 20px;
  }
  
  .title-section .page-title {
    font-size: 2rem;
  }
  
  .stats-card {
    gap: 20px;
    padding: 15px;
  }
  
  .stat-value {
    font-size: 1.5rem;
  }
}
</style>
